import React, { useState, useEffect, useRef } from 'react';
import { Link } from 'react-router-dom';
import { videoAPI } from '../services/api';
import { Video } from '../types';
import Avatar from '../components/Avatar';

const Following: React.FC = () => {
  const [videos, setVideos] = useState<Video[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [currentVideoIndex, setCurrentVideoIndex] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const videoRef = useRef<HTMLVideoElement>(null);
  const [touchStart, setTouchStart] = useState(0);
  const [touchEnd, setTouchEnd] = useState(0);

  useEffect(() => {
    fetchFollowingVideos();
  }, []);

  // 自动播放当前视频
  useEffect(() => {
    if (videoRef.current && videos.length > 0) {
      videoRef.current.load();
      videoRef.current.play().then(() => {
        setIsPlaying(true);
      }).catch(() => {
        setIsPlaying(false);
      });
    }
  }, [currentVideoIndex, videos]);

  const fetchFollowingVideos = async () => {
    try {
      setLoading(true);
      // TODO: 这里应该调用获取关注用户视频的API
      const videoList = await videoAPI.getVideos();
      // 模拟只显示关注用户的视频（前3个）
      const followingVideos = videoList.slice(0, 3);
      setVideos(followingVideos);
    } catch (error: any) {
      setError(error.message || '获取关注视频失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理触摸手势
  const handleTouchStart = (e: React.TouchEvent) => {
    setTouchStart(e.targetTouches[0].clientY);
  };

  const handleTouchMove = (e: React.TouchEvent) => {
    setTouchEnd(e.targetTouches[0].clientY);
  };

  const handleTouchEnd = () => {
    if (!touchStart || !touchEnd) return;
    
    const distance = touchStart - touchEnd;
    const isUpSwipe = distance > 50;
    const isDownSwipe = distance < -50;

    if (isUpSwipe && currentVideoIndex < videos.length - 1) {
      setCurrentVideoIndex(prev => prev + 1);
    } else if (isDownSwipe && currentVideoIndex > 0) {
      setCurrentVideoIndex(prev => prev - 1);
    }

    setTouchStart(0);
    setTouchEnd(0);
  };

  const handleVideoClick = () => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause();
        setIsPlaying(false);
      } else {
        videoRef.current.play();
        setIsPlaying(true);
      }
    }
  };

  const handleLike = async (video: Video) => {
    try {
      if (process.env.NODE_ENV === 'development') {
        console.log('点赞视频:', video.id);
      }
      setVideos(prev => prev.map(v => 
        v.id === video.id ? { ...v, likes: (v.likes || 0) + 1 } : v
      ));
    } catch (error) {
      if (process.env.NODE_ENV === 'development') {
        console.error('点赞失败:', error);
      }
    }
  };

  const handleComment = (video: Video) => {
    if (process.env.NODE_ENV === 'development') {
      console.log('评论视频:', video.id);
    }
  };

  const handleShare = (video: Video) => {
    if (process.env.NODE_ENV === 'development') {
      console.log('分享视频:', video.id);
    }
  };

  const handleFollow = async (video: Video) => {
    try {
      if (process.env.NODE_ENV === 'development') {
        console.log('关注用户:', video.userId);
      }
    } catch (error) {
      if (process.env.NODE_ENV === 'development') {
        console.error('关注失败:', error);
      }
    }
  };

  if (loading) {
    return (
      <div className="h-screen bg-black flex items-center justify-center">
        <div className="text-white text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-white mx-auto mb-4"></div>
          <p>加载中...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="h-screen bg-black flex items-center justify-center">
        <div className="text-white text-center">
          <p className="text-red-400 mb-4">{error}</p>
          <button 
            onClick={fetchFollowingVideos}
            className="bg-white text-black px-4 py-2 rounded"
          >
            重试
          </button>
        </div>
      </div>
    );
  }

  if (videos.length === 0) {
    return (
      <div className="h-screen bg-black flex items-center justify-center">
        <div className="text-white text-center">
          <div className="text-6xl mb-4">👥</div>
          <h3 className="text-xl font-medium mb-2">还没有关注内容</h3>
          <p className="text-gray-400 mb-4">关注你喜欢的创作者，获取最新内容</p>
          <Link to="/" className="bg-white text-black px-6 py-3 rounded">
            去发现更多内容
          </Link>
        </div>
      </div>
    );
  }

  const currentVideo = videos[currentVideoIndex];

  // 如果没有当前视频数据，显示加载状态
  if (!currentVideo) {
    return (
      <div className="h-screen bg-black flex items-center justify-center">
        <div className="text-white text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-white mx-auto mb-4"></div>
          <p>加载中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="h-screen bg-black relative overflow-hidden">
      {/* 视频播放区域 */}
      <div 
        className="relative w-full h-full"
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
      >
        <video
          ref={videoRef}
          src={currentVideo.videoUrl}
          poster={currentVideo.thumbnail}
          className="w-full h-full object-cover"
          loop
          muted
          playsInline
          onClick={handleVideoClick}
        />
        
        {/* 播放/暂停按钮 */}
        {!isPlaying && (
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="w-20 h-20 bg-black bg-opacity-50 rounded-full flex items-center justify-center">
              <svg className="w-10 h-10 text-white" fill="currentColor" viewBox="0 0 24 24">
                <path d="M8 5v14l11-7z"/>
              </svg>
            </div>
          </div>
        )}

        {/* 视频进度指示器 */}
        <div className="absolute bottom-0 left-0 right-0 h-1 bg-gray-800">
          <div className="h-full bg-red-500" style={{ width: `${(currentVideoIndex + 1) / videos.length * 100}%` }}></div>
        </div>

        {/* 右侧操作按钮 */}
        <div className="absolute right-4 bottom-20 flex flex-col items-center space-y-6">
          {/* 头像 */}
          <div className="relative">
            <Avatar user={{
              id: currentVideo.userId || 0,
              username: currentVideo.username || '未知用户',
              email: '',
              avatar: undefined,
              bio: '',
              createdAt: currentVideo.createdAt,
              updatedAt: currentVideo.createdAt
            }} size="lg" />
            <button
              onClick={() => handleFollow(currentVideo)}
              className="absolute -bottom-2 left-1/2 transform -translate-x-1/2 w-6 h-6 bg-red-500 rounded-full flex items-center justify-center"
            >
              <svg className="w-3 h-3 text-white" fill="currentColor" viewBox="0 0 24 24">
                <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
              </svg>
            </button>
          </div>

          {/* 点赞 */}
          <button
            onClick={() => handleLike(currentVideo)}
            className="flex flex-col items-center space-y-1"
          >
            <div className="w-12 h-12 bg-black bg-opacity-30 rounded-full flex items-center justify-center">
              <svg className="w-6 h-6 text-white" fill="currentColor" viewBox="0 0 24 24">
                <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
              </svg>
            </div>
            <span className="text-white text-sm">{currentVideo?.likes || 0}</span>
          </button>

          {/* 评论 */}
          <button
            onClick={() => handleComment(currentVideo)}
            className="flex flex-col items-center space-y-1"
          >
            <div className="w-12 h-12 bg-black bg-opacity-30 rounded-full flex items-center justify-center">
              <svg className="w-6 h-6 text-white" fill="currentColor" viewBox="0 0 24 24">
                <path d="M21.99 4c0-1.1-.89-2-2-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18zM18 14H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/>
              </svg>
            </div>
            <span className="text-white text-sm">评论</span>
          </button>

          {/* 分享 */}
          <button
            onClick={() => handleShare(currentVideo)}
            className="flex flex-col items-center space-y-1"
          >
            <div className="w-12 h-12 bg-black bg-opacity-30 rounded-full flex items-center justify-center">
              <svg className="w-6 h-6 text-white" fill="currentColor" viewBox="0 0 24 24">
                <path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92 1.61 0 2.92-1.31 2.92-2.92s-1.31-2.92-2.92-2.92z"/>
              </svg>
            </div>
            <span className="text-white text-sm">分享</span>
          </button>
        </div>

        {/* 底部视频信息 */}
        <div className="absolute bottom-20 left-4 right-20 text-white">
          <div className="mb-2">
            <span className="font-bold text-lg">@{currentVideo.username || '未知用户'}</span>
          </div>
          <div className="mb-2">
            <p className="text-sm">{currentVideo.title}</p>
          </div>
          <div className="flex items-center space-x-4 text-sm text-gray-300">
            <span>#{currentVideo.username || '未知用户'}</span>
            <span>{currentVideo.views || 0} 次观看</span>
          </div>
        </div>

        {/* 顶部导航 */}
        <div className="absolute top-0 left-0 right-0 flex justify-center pt-12 pb-4">
          <div className="flex space-x-8">
            <button className="text-gray-400">
              推荐
            </button>
            <button className="text-white font-bold border-b-2 border-white pb-1">
              关注
            </button>
            <button className="text-gray-400">
              附近
            </button>
          </div>
        </div>

        {/* 视频切换指示器 */}
        <div className="absolute top-20 right-4 text-white text-sm">
          {currentVideoIndex + 1} / {videos.length}
        </div>
      </div>

      {/* 上下滑动切换视频的提示 */}
      <div className="absolute right-4 top-1/2 transform -translate-y-1/2 text-white text-center opacity-50">
        <div className="w-8 h-8 border-2 border-white rounded-full flex items-center justify-center mb-2">
          <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
            <path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"/>
          </svg>
        </div>
        <span className="text-xs">上滑切换</span>
      </div>
    </div>
  );
};

export default Following; 